package cn.ffcs.unm.testClient.util;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;

import cn.ffcs.unm.testClient.manager.IdCardInfoManager;
import cn.ffcs.unm.testClient.vo.Input;
import cn.ffcs.uom.common.util.ApplicationContextUtil;
import cn.ffcs.uom.common.util.StrUtil;

import com.alibaba.fastjson.JSONObject;

/**
 * 调国政通实名制校验接口 Title:
 * 
 * @Description:
 * @Copyright: FFCS（C） 2017
 * @Company: FFCS
 * @author Wang Yiren
 * @Version 0.0.1 date:2017年11月14日
 * @since JDK1.6
 */
public class GztJsonUtil {

	private static IdCardInfoManager idCardInfoManager = (IdCardInfoManager) ApplicationContextUtil
			.getBean("idCardInfoManager");

	public static String GZT_URL = "http://127.0.0.1:9001/muiltcompare/";//国政通实名制校验接口地址

	/**
	 * 实名制校验
	 * 
	 * @param idNum
	 * @param idName
	 *            `
	 * @return
	 */
	public static boolean checkIdCard(String idNum, String idName) {
		if (StrUtil.isNullOrEmpty(idNum) || StrUtil.isNullOrEmpty(idName)) {
			return false;
		} else if (idCardInfoManager.getCertIdVarInfo(idNum, idName) != null) {
			return true;
		} else {
			Input input = new Input();
			input.setClientSn("201710301429385880000000001");
			input.setSign("0ca175b9c0f726a831d895e269332461");
			input.setGmsfhm(idNum);
			input.setXm(idName);
			String javaBeanJson = input.toString();

			HttpClient httpClient = new HttpClient();
			PostMethod httpPost = new PostMethod(GztJsonUtil.GZT_URL);
			try {
				StringRequestEntity requestEntity = new StringRequestEntity(
						javaBeanJson, "application/json", "UTF-8");
				httpPost.setRequestEntity(requestEntity);
				httpClient.executeMethod(httpPost);
				// 获取返回的状态码
				String statusCode = String.valueOf(httpPost.getStatusCode());
				String returnCode = null;
				if (!"200".equals(statusCode)) {
					returnCode = statusCode;
					return false;
				}
				//设置响应数据的字符集
				httpPost.getParams().setContentCharset("UTF-8");
				//获取响应的数据
				String bodyAsString = httpPost.getResponseBodyAsString();
				JSONObject jsonObject = JSONObject.parseObject(bodyAsString);
				//获取返回数据中的状态码
				returnCode = jsonObject.getString("resultCode");
				// String returnMsg = jsonObject.getString("resultMsg");
				if ("00".equals(returnCode)) {
					boolean saveIdCardFlag = idCardInfoManager
							.SaveIdCardInformation(idNum, idName);
					if (saveIdCardFlag) {
						return true;
					}
					return false;
				}

			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (HttpException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
		return false;
	}
}
